﻿using System.Collections;
using System.Collections.Generic;
using System;
using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEngine;
using UnityEngine.Rendering;

public class BaseShaderGUI : CustomShaderGUI
{
    private const string shader_path = "Shader/Game";//自定义shader路径

    private static Dictionary<string, string> shaderNameDic = new Dictionary<string, string>();
    protected override void FindProperties(MaterialProperty[] properties)
    {
        
    }

    protected override void OnShaderGUI(MaterialEditor materialEditor, Material[] materials)
    {
       // ShaderListGUI(materialEditor, materials);
    }

    private static string GetAndCacheShaderName(string shaderFileName)
    {
        if (shaderNameDic.ContainsKey(shaderFileName))
        {
            return shaderNameDic[shaderFileName];
        }

        Shader shader = AssetDatabase.LoadAssetAtPath<Shader>(string.Format("Assets/{0}/{1}.shader", shader_path, shaderFileName));
        if (null == shader)
        {
            return "Path isnot Find : "+ shader_path+"/"+ shaderFileName;
        }

        shaderNameDic.Add(shaderFileName, shader.name);
        return shader.name;
    }
    // 获得原始shader的名字（在shader中的名字)
    private static string GetOrginalShaderName(string shaderName)
    {
        if (shaderName.IndexOf("AutoBuild/") < 0) return shaderName;

        string orignalShaderName = shaderName.Replace("AutoBuild/", "");
        orignalShaderName = orignalShaderName.Substring(0, orignalShaderName.IndexOf("__KW__"));
        return orignalShaderName;
    }

    private void ShaderListGUI(MaterialEditor materialEditor, Material[] materials)
    {
        string[] fileList = Directory.GetFiles(
         Path.Combine(Application.dataPath, shader_path),
         "*shader",
         SearchOption.TopDirectoryOnly);
        string shaderName = "";
        List<string> shaderList = new List<string>();
        foreach (var item in fileList)
        {
            shaderName = GetAndCacheShaderName(Path.GetFileNameWithoutExtension(item));
            shaderList.Add(shaderName);
        }

        shaderList.Sort();
        int selectIndex = -1;
        shaderName = (materialEditor.target as Material).shader.name;
        shaderName = GetOrginalShaderName(shaderName); // 有可能shader是被打包阶断处理过的

        for (int i = 0; i < shaderList.Count; i++)
        {
            if (shaderName == shaderList[i])
            {
                selectIndex = i;
            }
        }

        if (selectIndex == -1)
        {
            return;
        }

        EditorGUI.BeginChangeCheck();
        selectIndex = EditorGUILayout.Popup("ShaderName:", selectIndex, shaderList.ToArray());
        if (EditorGUI.EndChangeCheck())
        {
            shaderName = shaderList[selectIndex];
            (materialEditor.target as Material).shader = Shader.Find(shaderName);
        }
    }
}
